﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Transactions;
using System.Data.SqlClient;

using Global.Class.Library;
using DataTransferObject;
using DataTransferObject.MetaDataList;
using DataAccessLayer;
using DataAccessLayer.MetaDataList;
using DataAccessLayer.MetaDataList.ListItemPM_APMDTSTableAdapters;

namespace BusinessLogicLayer.MetaDataList
{
    public class ListItemPM_APMBLL : NotifyPropertyChangeObject
    {
        public GlobalEnum.TaskID TaskID { get { return GlobalEnum.TaskID.ListItemPM_APM; } }

        private UserInformation userOrganization;

        private ListItemPM_APMMaster listItemPM_APMMaster;

        private BindingList<ListItemPM_APMDetail> listItemPM_APMDetailList;



        public ListItemPM_APMBLL()
        {
            try
            {
                if (GlobalVariables.shouldRestoreProcedure) RestoreProcedure();

                userOrganization = new UserInformation();

                listItemPM_APMMaster = new ListItemPM_APMMaster();

                this.listItemPM_APMDetailList = new BindingList<ListItemPM_APMDetail>();

                GlobalDefaultValue.Apply(this);


                this.ListItemPM_APMMaster.PropertyChanged += new PropertyChangedEventHandler(ListItemPM_APMMaster_PropertyChanged);

                this.ListItemPM_APMDetailList.ListChanged += new ListChangedEventHandler(ListItemPM_APMDetailList_ListChanged);

            }
            catch (Exception exception)
            {
                throw exception;
            }
        }

        private void ListItemPM_APMMaster_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            this.SetDirty();
        }

        private void ListItemPM_APMDetailList_ListChanged(object sender, ListChangedEventArgs e)
        {
            this.SetDirty();
        }




        #region <Adapter>

        private ListItemPM_APMListingTableAdapter listingTableAdapter;
        protected ListItemPM_APMListingTableAdapter ListingTableAdapter
        {
            get
            {
                if (listingTableAdapter == null) listingTableAdapter = new ListItemPM_APMListingTableAdapter();
                return listingTableAdapter;
            }
        }

        private ListItemPM_APMTableAdapter masterTableAdapter;
        protected ListItemPM_APMTableAdapter MasterTableAdapter
        {
            get
            {
                if (masterTableAdapter == null) masterTableAdapter = new ListItemPM_APMTableAdapter();
                return masterTableAdapter;
            }
        }

        private ListItemPM_APMDetailTableAdapter detailTableAdapter;
        protected ListItemPM_APMDetailTableAdapter DetailTableAdapter
        {
            get
            {
                if (detailTableAdapter == null) detailTableAdapter = new ListItemPM_APMDetailTableAdapter();
                return detailTableAdapter;
            }
        }


        #endregion <Adapter>

        #region <Storage>

        public UserInformation UserOrganization
        {
            get { return this.userOrganization; }
            set { this.userOrganization = value; }
        }

        public ListItemPM_APMDTS.ListItemPM_APMListingDataTable ListItemPM_APMListing()
        {
            return this.ListingTableAdapter.GetData();
        }

        public ListItemPM_APMMaster ListItemPM_APMMaster
        {
            get { return this.listItemPM_APMMaster; }
        }

        public BindingList<ListItemPM_APMDetail> ListItemPM_APMDetailList
        {
            get { return this.listItemPM_APMDetailList; }
        }


        #endregion <Storage>

        #region Properties

        #region <Primary Key>

        public int ItemPM_APMID   //Primary Key
        {
            get { return this.ListItemPM_APMMaster.ItemPM_APMID; }
            private set
            {
                if (this.ListItemPM_APMMaster.ItemPM_APMID != value)
                {
                    this.StopTracking();

                    this.ListItemPM_APMMaster.ItemPM_APMID = value;

                    this.ListItemPM_APMGetMaster();
                    this.ListItemPM_APMGetDetail();

                    this.StartTracking();
                    this.Reset();
                }

            }
        }

        #endregion <Primary Key>

        private void ListItemPM_APMGetMaster()
        {
            if (this.ItemPM_APMID > 0)
            {
                ListItemPM_APMDTS.ListItemPM_APMDataTable masterDataTable = this.MasterTableAdapter.GetData(this.ItemPM_APMID);

                if (masterDataTable.Count > 0)
                {
                    this.ListItemPM_APMMaster.StopTracking();

                    this.ListItemPM_APMMaster.EntryDate = masterDataTable[0].EntryDate;

                    this.ListItemPM_APMMaster.AncestorID = masterDataTable[0].AncestorID;                    

                    this.ListItemPM_APMMaster.Description = masterDataTable[0].Description;
                    this.ListItemPM_APMMaster.Other = masterDataTable[0].Other;

                    this.ListItemPM_APMMaster.StartTracking();

                    this.ListItemPM_APMMaster.Reset();

                    this.UserOrganization.UserID = masterDataTable[0].UserID;
                    this.UserOrganization.UserOrganizationID = masterDataTable[0].UserOrganizationID;
                }
                else throw new System.ArgumentException("Insufficient get data");
            }
            else
            {
                GlobalDefaultValue.Apply(this.ListItemPM_APMMaster);
                this.ListItemPM_APMMaster.EntryDate = DateTime.Today;
                this.ListItemPM_APMMaster.Reset();
            }
        }


        private void ListItemPM_APMGetDetail()
        {
            this.listItemPM_APMDetailList.RaiseListChangedEvents = false;
            this.listItemPM_APMDetailList.Clear();
            if (this.ItemPM_APMID >= 0)
            {

                ListItemPM_APMDTS.ListItemPM_APMDetailDataTable detailDataTable = this.DetailTableAdapter.GetData(this.ItemPM_APMID);

                if (detailDataTable.Count > 0)
                {
                    foreach (ListItemPM_APMDTS.ListItemPM_APMDetailRow detailRow in detailDataTable.Rows)
                    {
                        this.listItemPM_APMDetailList.Add(new ListItemPM_APMDetail(detailRow.CommonID, detailRow.CommonValue, detailRow.Remarks));
                    }
                }
            }
            this.listItemPM_APMDetailList.RaiseListChangedEvents = true;
            this.listItemPM_APMDetailList.ResetBindings();
        }

        #endregion Properties





        #region Object Permission

        public override bool IsValid
        {
            get
            {
                List<ListItemPM_APMDetail> inValidListItemPM_APMDetail = this.ListItemPM_APMDetailList.Where(listItemPM_APMDetail => !listItemPM_APMDetail.IsValid).ToList();
                return this.ListItemPM_APMMaster.IsValid && inValidListItemPM_APMDetail.Count == 0;
            }
        }

        public bool ReadOnly
        {
            get
            {
                try
                {
                    return GlobalUserPermission.GetUserReadOnly(GlobalVariables.GlobalUserInformation.UserID, this.TaskID);
                }
                catch
                {
                    return true;
                }
            }
        }

        public bool Editable
        {
            get
            {
                try
                {
                    if (!GlobalUserPermission.GetUserEditable(GlobalVariables.GlobalUserInformation.UserID, this.TaskID, this.UserOrganization.UserOrganizationID)) return false;

                    return GlobalUserPermission.GetEditable("ListItemPM_APMEditable", this.ItemPM_APMID);
                }
                catch
                {
                    return false;
                }
            }
        }

        public bool Verifiable
        {
            get
            {
                try
                {
                    if (!GlobalUserPermission.GetUserEditable(GlobalVariables.GlobalUserInformation.UserID, GlobalEnum.TaskID.ListItemPM_APMVerifiable, this.UserOrganization.UserOrganizationID)) return false;

                    return GlobalUserPermission.GetEditable("ListItemPM_APMEditable", this.ItemPM_APMID);
                }
                catch
                {
                    return false;
                }
            }
        }

        public bool Unverifiable
        {
            get
            {
                try
                {
                    if (!GlobalUserPermission.GetUserEditable(GlobalVariables.GlobalUserInformation.UserID, GlobalEnum.TaskID.ListItemPM_APMUnverifiable, this.UserOrganization.UserOrganizationID)) return false;

                    return GlobalUserPermission.GetEditable("ListItemPM_APMEditable", this.ItemPM_APMID);
                }
                catch
                {
                    return false;
                }
            }
        }


        #endregion Object Permission






        public void Fill(int itemPM_APMID)
        {
            if (this.ItemPM_APMID == itemPM_APMID) this.ItemPM_APMID = -1; //Enforce to reload
            this.ItemPM_APMID = itemPM_APMID;
        }

        public void New()
        {
            if (this.ItemPM_APMID == 0) this.ItemPM_APMID = -1;
            this.ItemPM_APMID = 0;
        }

        public void Edit()
        {

        }

        #region Save & Delete Method


        public bool Save()
        {
            int itemPM_APMID = 0;

            try
            {

                if (!this.SaveValidate()) throw new System.ArgumentException("Insufficient save", "Save validate");

                using (TransactionScope transactionScope = new TransactionScope())
                {
                    if (this.ReadOnly) throw new System.ArgumentException("Insufficient save", "Uneditable");

                    if (!this.SaveMaster(ref itemPM_APMID)) throw new System.ArgumentException("Insufficient save", "Save master");

                    if (!this.SaveDetail(itemPM_APMID)) throw new System.ArgumentException("Insufficient save", "Save detail");

                    transactionScope.Complete();
                }

                SQLDatabase.ExecuteNonQuery("ListItemPM_APMUpdateHierarchyLevel", CommandType.StoredProcedure, "AncestorID", this.listItemPM_APMMaster.AncestorID);

                this.Fill(itemPM_APMID);
                return true;
            }
            catch (System.Exception exception)
            {
                throw exception;
            }
        }


        public bool Delete()
        {
            if (this.listItemPM_APMMaster.ItemPM_APMID <= 0) return false;

            try
            {

                if (!this.SaveValidate()) throw new System.ArgumentException("Insufficient delete", "Delete validate");

                using (TransactionScope transactionScope = new TransactionScope())
                {
                    if (!this.Editable) throw new System.ArgumentException("Insufficient delete", "Uneditable");

                    if (!this.SaveUndo(this.listItemPM_APMMaster.ItemPM_APMID)) throw new System.ArgumentException("Insufficient delete", "Delete detail");

                    if (this.MasterTableAdapter.Delete(this.listItemPM_APMMaster.ItemPM_APMID) != 1) throw new System.ArgumentException("Insufficient delete", "Delete master");

                    transactionScope.Complete();
                }
                this.Fill(0);
                return true;
            }
            catch (System.Exception exception)
            {
                throw exception;
            }
        }


        private bool SaveValidate()
        {
            ExceptionTable exceptionTable = new ExceptionTable(new string[2, 2] { { "ExceptionCategory", "System.String" }, { "ExceptionDescription", "System.String" } });

            this.UserOrganization = GlobalUserPermission.GetUserInformation(this.UserOrganization.UserID, this.ListItemPM_APMMaster.EntryDate);

            if (this.UserOrganization.UserID <= 0 || this.UserOrganization.UserOrganizationID <= 0) exceptionTable.AddException(new string[] { GlobalVariables.stringFieldRequired, "User information" });

            if (exceptionTable.Table.Rows.Count <= 0 && this.IsValid) return true; else throw new CustomException("Save validate", exceptionTable.Table);
        }


        private bool SaveMaster(ref int itemPM_APMID)
        {
            ListItemPM_APMDTS.ListItemPM_APMDataTable masterDataTable;
            ListItemPM_APMDTS.ListItemPM_APMRow masterRow;

            if (this.listItemPM_APMMaster.ItemPM_APMID <= 0) //Add
            {
                masterDataTable = new ListItemPM_APMDTS.ListItemPM_APMDataTable();
                masterRow = masterDataTable.NewListItemPM_APMRow();
            }
            else //Edit
            {
                if (!this.SaveUndo(listItemPM_APMMaster.ItemPM_APMID)) throw new System.ArgumentException("Insufficient save", "Save undo");
                masterDataTable = this.MasterTableAdapter.GetData(listItemPM_APMMaster.ItemPM_APMID);
                if (masterDataTable.Count > 0) masterRow = masterDataTable[0]; else throw new System.ArgumentException("Insufficient save", "Get for edit");
            }

            masterRow.EntryDate = this.listItemPM_APMMaster.EntryDate;

            masterRow.AncestorID = this.listItemPM_APMMaster.AncestorID;
            masterRow.HierarchyLevel = 0;
            masterRow.HierarchyOrder = "";

            masterRow.Description = this.listItemPM_APMMaster.Description;
            masterRow.Other = this.listItemPM_APMMaster.Other;

            masterRow.UserID = this.UserOrganization.UserID;
            masterRow.UserOrganizationID = this.UserOrganization.UserOrganizationID;

            if (this.listItemPM_APMMaster.ItemPM_APMID <= 0) masterDataTable.AddListItemPM_APMRow(masterRow);

            int rowsAffected = this.MasterTableAdapter.Update(masterRow);

            itemPM_APMID = masterRow.ItemPM_APMID;

            return rowsAffected == 1;

        }


        private bool SaveDetail(int itemPM_APMID)
        {
            int serialID = 0; int rowsAffected = 0;


            #region <Save collection>

            serialID = 0;

            ListItemPM_APMDTS.ListItemPM_APMDetailDataTable detailDataTable = new ListItemPM_APMDTS.ListItemPM_APMDetailDataTable();

            foreach (ListItemPM_APMDetail listItemPM_APMDetail in this.ListItemPM_APMDetailList)
            {
                ListItemPM_APMDTS.ListItemPM_APMDetailRow detailRow = detailDataTable.NewListItemPM_APMDetailRow();

                detailRow.ItemPM_APMID = itemPM_APMID;
                detailRow.SerialID = ++serialID;

                detailRow.CommonID = listItemPM_APMDetail.CommonID;
                detailRow.CommonValue = listItemPM_APMDetail.CommonValue;

                detailRow.Remarks = listItemPM_APMDetail.Remarks;

                detailDataTable.AddListItemPM_APMDetailRow(detailRow);
            }

            rowsAffected = this.DetailTableAdapter.Update(detailDataTable);
            if (rowsAffected != this.listItemPM_APMDetailList.Count) throw new System.ArgumentException("Insufficient save", "Save detail");


            #endregion <Save collection>


            return true;
        }


        private bool SaveUndo(int itemPM_APMID)
        {
            this.DetailTableAdapter.Delete(itemPM_APMID);

            return true;
        }



        #endregion



        private void RestoreProcedure()
        {
            string queryString;
            string[] queryArray;



            queryString = "     " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       SELECT      ItemPM_APMID, Description, AncestorID, Other, EntryDate " + "\r\n";
            queryString = queryString + "       FROM        ListItemPM_APM " + "\r\n";
            queryString = queryString + "       ORDER BY    Description " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListItemPM_APMListing", queryString);



            queryString = "     @ItemPM_APMID Int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       SELECT      ItemPM_APMID, Description, AncestorID, HierarchyLevel, HierarchyOrder, Other, EntryDate, UserID, UserOrganizationID " + "\r\n";
            queryString = queryString + "       FROM        ListItemPM_APM " + "\r\n";
            queryString = queryString + "       WHERE       ItemPM_APMID = @ItemPM_APMID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListItemPM_APMSelect", queryString);


            queryString = "     @Description nvarchar(100),	@AncestorID int, @HierarchyLevel int, @HierarchyOrder nvarchar(50), @Other nvarchar(100), @EntryDate datetime, @UserID int, @UserOrganizationID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       INSERT INTO ListItemPM_APM (Description, AncestorID, HierarchyLevel, HierarchyOrder, Other, EntryDate, UserID, UserOrganizationID) VALUES (@Description, @AncestorID, @HierarchyLevel, @HierarchyOrder, @Other, @EntryDate, @UserID, @UserOrganizationID) " + "\r\n";
            queryString = queryString + "       SELECT      ItemPM_APMID, Description, AncestorID, HierarchyLevel, HierarchyOrder, Other, EntryDate, UserID, UserOrganizationID FROM ListItemPM_APM WHERE ItemPM_APMID = SCOPE_IDENTITY() " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListItemPM_APMInsert", queryString);


            queryString = "     @ItemPM_APMID int, @Description nvarchar(100), @AncestorID int, @HierarchyLevel int, @HierarchyOrder nvarchar(50), @Other nvarchar(100), @EntryDate datetime, @UserID int, @UserOrganizationID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       UPDATE      ListItemPM_APM SET Description = @Description, AncestorID = @AncestorID, HierarchyLevel = @HierarchyLevel, HierarchyOrder = @HierarchyOrder, Other = @Other, EntryDate = @EntryDate, UserID = @UserID, UserOrganizationID = @UserOrganizationID WHERE ItemPM_APMID = @ItemPM_APMID " + "\r\n";
            queryString = queryString + "       SELECT      ItemPM_APMID, Description, AncestorID, HierarchyLevel, HierarchyOrder, Other, EntryDate, UserID, UserOrganizationID FROM ListItemPM_APM WHERE ItemPM_APMID = @ItemPM_APMID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListItemPM_APMUpdate", queryString);


            queryString = " @ItemPM_APMID int ";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       DELETE FROM ListItemPM_APM WHERE ItemPM_APMID = @ItemPM_APMID " + "\r\n";
            SQLDatabase.CreateStoredProcedure("ListItemPM_APMDelete", queryString);






            queryString = " @ItemPM_APMID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       SELECT      ItemPM_APMID, SerialID, CommonID, CommonValue, Remarks " + "\r\n";
            queryString = queryString + "       FROM        ListItemPM_APMDetail " + "\r\n";
            queryString = queryString + "       WHERE       ItemPM_APMID = @ItemPM_APMID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListItemPM_APMDetailSelect", queryString);


            queryString = " @ItemPM_APMID int, @SerialID int,	@CommonID int, @CommonValue float, @Remarks nvarchar(100) " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       INSERT INTO ListItemPM_APMDetail (ItemPM_APMID, SerialID, CommonID, CommonValue, Remarks) VALUES (@ItemPM_APMID, @SerialID, @CommonID, @CommonValue, @Remarks) " + "\r\n";
            queryString = queryString + "       SELECT      ItemPM_APMID, SerialID, CommonID, CommonValue, Remarks FROM ListItemPM_APMDetail WHERE (ItemPM_APMID = @ItemPM_APMID) AND (SerialID = @SerialID) " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListItemPM_APMDetailInsert", queryString);



            queryString = " @ItemPM_APMID int, @SerialID int,	@CommonID int, @CommonValue float, @Remarks nvarchar(100) " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       UPDATE      ListItemPM_APMDetail SET CommonID = @CommonID, CommonValue = @CommonValue, Remarks = @Remarks WHERE ItemPM_APMID = @ItemPM_APMID AND SerialID = @SerialID " + "\r\n";
            queryString = queryString + "       SELECT      ItemPM_APMID, SerialID, CommonID, CommonValue, Remarks FROM ListItemPM_APMDetail WHERE ItemPM_APMID = @ItemPM_APMID AND SerialID = @SerialID " + "\r\n";

            SQLDatabase.CreateStoredProcedure("ListItemPM_APMDetailUpdate", queryString);



            queryString = " @ItemPM_APMID int " + "\r\n";
            queryString = queryString + " WITH ENCRYPTION " + "\r\n";
            queryString = queryString + " AS " + "\r\n";
            queryString = queryString + "       DELETE FROM ListItemPM_APMDetail WHERE ItemPM_APMID = @ItemPM_APMID " + "\r\n";
            SQLDatabase.CreateStoredProcedure("ListItemPM_APMDetailDelete", queryString);



            queryString = " @AncestorID Int ";
            queryString = queryString + " WITH ENCRYPTION ";
            queryString = queryString + " AS ";

            queryString = queryString + "   DECLARE @AncestorHierarchyOrder NVarchar(30), @AncestorHierarchyLevel Int  ";
            queryString = queryString + "   DECLARE @Cursor_Rows Int, @SerialNo Int ";

            queryString = queryString + "   SET @AncestorHierarchyOrder = N'' ";
            queryString = queryString + "   SET @AncestorHierarchyLevel = 0 ";
            queryString = queryString + "   SET @SerialNo = 0 ";
            queryString = queryString + "   SET @Cursor_Rows = 0 ";

            queryString = queryString + "   IF @AncestorID <> 0 ";
            queryString = queryString + "   BEGIN ";

            queryString = queryString + "       DECLARE Ancestor_Cursor CURSOR LOCAL FOR ";
            queryString = queryString + "       SELECT TOP 1 HierarchyOrder, HierarchyLevel FROM ListItemPM_APM ";
            queryString = queryString + "       WHERE ItemPM_APMID = @AncestorID ";

            queryString = queryString + "       OPEN Ancestor_Cursor ";

            queryString = queryString + "       FETCH NEXT FROM Ancestor_Cursor INTO @AncestorHierarchyOrder, @AncestorHierarchyLevel ";

            queryString = queryString + "       CLOSE Ancestor_Cursor ";
            queryString = queryString + "       DEALLOCATE Ancestor_Cursor ";


            queryString = queryString + "   END ";

            queryString = queryString + "   DECLARE @ItemPM_APMID Int ";

            queryString = queryString + "   DECLARE ItemPM_APM_Cursor CURSOR LOCAL SCROLL FOR ";
            queryString = queryString + "   SELECT ItemPM_APMID FROM ListItemPM_APM ";
            queryString = queryString + "   WHERE AncestorID = @AncestorID ORDER BY Description ";
            queryString = queryString + "   FOR UPDATE ";

            queryString = queryString + "   OPEN ItemPM_APM_Cursor ";

            queryString = queryString + "   FETCH LAST FROM ItemPM_APM_Cursor INTO @ItemPM_APMID ";
            queryString = queryString + "   IF @@FETCH_STATUS = 0 ";
            queryString = queryString + "   BEGIN ";
            queryString = queryString + "       SET @Cursor_Rows = @@CURSOR_ROWS ";
            queryString = queryString + "       FETCH FIRST FROM ItemPM_APM_Cursor INTO @ItemPM_APMID ";
            queryString = queryString + "   END ";

            queryString = queryString + "   WHILE @@FETCH_STATUS = 0";
            queryString = queryString + "   BEGIN";

            queryString = queryString + "       SET @SerialNo = @SerialNo + 1 ";

            queryString = queryString + "       UPDATE ListItemPM_APM SET HierarchyOrder = @AncestorHierarchyOrder +  REPLICATE('0', DATALENGTH(CONVERT (NVarchar(30), @Cursor_Rows)) - DATALENGTH(CONVERT (NVarchar(30), @SerialNo))) + CONVERT (NVarchar(30), @SerialNo), HierarchyLevel = @AncestorHierarchyLevel + 1 ";
            queryString = queryString + "       WHERE CURRENT OF ItemPM_APM_Cursor ";

            queryString = queryString + "       EXECUTE ListItemPM_APMUpdateHierarchyLevel @AncestorID = @ItemPM_APMID ";

            queryString = queryString + "       FETCH NEXT FROM ItemPM_APM_Cursor INTO @ItemPM_APMID ";

            queryString = queryString + "   END ";

            queryString = queryString + "   CLOSE ItemPM_APM_Cursor ";
            queryString = queryString + "   DEALLOCATE ItemPM_APM_Cursor ";

            SQLDatabase.CreateStoredProcedure("ListItemPM_APMUpdateHierarchyLevel", queryString);



            /// <summary>
            /// Check for editable
            /// </summary>
            queryArray = new string[2];
            queryArray[0] = "   SELECT      TOP 1 ItemPM_APMID FROM ListItemPM_APM WHERE AncestorID = @FindIdentityID " ;
            queryArray[1] = "   SELECT      TOP 1 ItemPM_APMID FROM ListItemCommodity WHERE ItemPM_APMID = @FindIdentityID " ;

            SQLDatabase.CreateProcedureToCheckExisting("ListItemPM_APMEditable", queryArray);

        }        

    }
}
